//
//  WHNetworkManager.m
//  LvZhongMagicKey
//
//  Created by 邓伟浩 on 2017/12/16.
//  Copyright © 2017年 邓伟浩. All rights reserved.
//

#import "WHNetworkManager.h"
#import "WHDataCache.h"
#import "UIViewController+WHTopViewController.h"


@implementation WHNetworkManager

+ (UIView *)getCurrentView {
    UIViewController *controller = [UIViewController topViewController];
    return controller.view;
}

+ (NSURLSessionDownloadTask *)downLoadWithUrl:(NSString *)urlString
               fileName:(NSString *)fileName
               progress:(void (^)(double))progress
                Success:(void (^)(id))success
                failure:(void (^)(NSError *))failure {
    NSURLSessionDownloadTask *downloadTask;
    DLog(@"%@", NSHomeDirectory());
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer.timeoutInterval = 30;
    
    [MBProgressHUD showCircularHUDProgress];
    // 创建下载任务
    downloadTask = [sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD getHUDProgress].progress = downloadProgress.fractionCompleted;
        });
        if (progress) {
            progress(downloadProgress.fractionCompleted);//完成的百分比
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSURL *pathURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
        
        NSString *suggestedFilename = [response suggestedFilename];
        if (ValidStr(fileName)) {
            NSString *realFileName = NSStringFormat(@"%@.%@", fileName, suggestedFilename.pathExtension);
            return [pathURL URLByAppendingPathComponent:realFileName];
        } else {
            return [pathURL URLByAppendingPathComponent:suggestedFilename];
        }
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (!error) {
            //隐藏
            [MBProgressHUD hideHUD];
            //下载成功
            [MBProgressHUD showCustomViewHUD:@"下载成功！" imageName:@"icon_downSuccess"];
            
            //文件名称
            NSString *fileName = filePath.lastPathComponent;
            //沙盒documents路径
            NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            //文件路径
            NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsPath, fileName];
            
            NSData *dataURL = [NSData dataWithContentsOfFile:filePath];
            
            if (success) {
                success(dataURL);
            }
        } else {
            [WHView showHudMsg:@"下载失败！"];
            
            if (failure) {
                failure(error);
            }
        }
    }];
    
    //开始任务
    [downloadTask resume];
    
    return downloadTask;
}

+ (NSURLSessionDataTask *)upLoadFileWithUrlStr:(NSString *)urlStr parameters:(id)parameters fileName:(NSString *)fileName filePath:(NSString *)filePath name:(NSString *)name Success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    UIView *currentView = [self getCurrentView];
    [MBProgressHUD showHudInView:currentView];
    
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
    NSURLSessionDataTask *task = [manger POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:filePath.pathExtension];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:currentView];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:currentView];
        if (failure) {
            failure(error);
        }
        
    }];
    return task;
}

// 上传图片
+ (NSURLSessionDataTask *)upLoadImageWithUrlStr:(NSString *)urlStr parameters:(id)parameters imageData:(NSData *)imageData fileName:(NSString *)fileName name:(NSString *)name Success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    UIView *currentView = [self getCurrentView];
    [MBProgressHUD showHudInView:currentView];
    
    NSURLSessionDataTask *task = [manger POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:currentView];
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:currentView];
        if (failure) {
            failure(error);
        }
        
    }];
    return task;
}

// 请求url数据
+ (NSURLSessionDataTask *)requestWithURL:(NSString *)urlStr parameters:(id)parameters isUpData:(BOOL)is Success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
    NSURLSessionDataTask *task;
    //    DLog(@"%@", NSHomeDirectory());
    
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusUnknown || [AFNetworkReachabilityManager sharedManager].isReachable) {
        WHDataCache *dataCache = [WHDataCache sharedDataCache];
        
        if (is) {
            // 存在文件 - 删除原有
            [dataCache deleteDataWithNameString:urlStr];
        }
        NSData *data = [dataCache getDataWithNameString:urlStr];
        if (!data) {
//            文件不存在,开始下载...
            
            DLog(@"————正在加载———— %@", urlStr);
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            manager.requestSerializer.timeoutInterval = 30;
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];
            
            UIView *currentView = [self getCurrentView];
            [MBProgressHUD showHudInView:currentView];
            
            task = [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //将数据存入缓存
                DLog(@"————加载成功———— %@", urlStr);
                [MBProgressHUD hideHUDForView:currentView];
                if (success) {
                    success(responseObject);
                }
                WHDataCache *dataCache = [WHDataCache sharedDataCache];
                if (responseObject != nil) {
                    NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
                    [dataCache saveData:data andNameString:urlStr];
                } else {
                    DLog(@"返回数据错误");
                    
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [MBProgressHUD hideHUDForView:currentView];
                NSString *errorStr = NSStringFormat(@"%ld \n %@ \n%@", (long)error.code, error.localizedDescription, urlStr);
                DLog(@"%@", errorStr);
                
#if DEBUG
                [WHView showAlertwithTitle:@"异常错误" message:errorStr okAction:^(UIAlertAction *action) {
                } cancelAction:nil];
#endif
                
                if (failure) {
                    failure(error);
                }
            }];
            
            
        } else {
            // 文件存在
            if (success) {
                DLog(@"加载缓存成功!");
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                success(dic);
            }
        }

    } else {
        DLog(@"断开网络连接 %@", urlStr);
        [WHView showAlertwithTitle:@"网络连接失败" message:@"请检查网络设置" okAction:^(UIAlertAction *action) {
        } cancelAction:nil];
        
        if (failure) {
            failure(nil);
        }
    }
    
    return task;
}

+ (NSURLSessionDataTask *)requestWithURL:(NSString *)urlStr
            parameters:(id)parameters
               Success:(void (^)(id responseObject))success
               failure:(void (^)(NSError *error))failure {
    NSURLSessionDataTask *task;
    
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusUnknown || [AFNetworkReachabilityManager sharedManager].isReachable) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.requestSerializer.timeoutInterval = 30;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain", nil];
        
        task = [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (responseObject != nil) {
                if (success) {
                    success(responseObject);
                }
            } else {
                DLog(@"返回数据错误");
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSString *errorStr = NSStringFormat(@"%ld \n %@ \n%@", (long)error.code, error.localizedDescription, urlStr);
            DLog(@"%@", errorStr);
            
#if DEBUG
            [WHView showAlertwithTitle:@"异常错误" message:errorStr okAction:^(UIAlertAction *action) {
            } cancelAction:nil];
#endif
            
            if (failure) {
                failure(error);
            }
        }];
        
    } else {
        DLog(@"断开网络连接 %@", urlStr);
        [WHView showAlertwithTitle:@"网络连接失败" message:@"请检查网络设置" okAction:^(UIAlertAction *action) {
        } cancelAction:nil];
        
        if (failure) {
            failure(nil);
        }
    }
    
    return task;
}

+ (void)checkNetworkAvailable:(NetworkStatusBlock)showNetworkStatus {
    //开始监听网络
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        DLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                showNetworkStatus(YES, AFNetworkReachabilityStatusReachableViaWWAN);
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                showNetworkStatus(YES, AFNetworkReachabilityStatusReachableViaWiFi);
                break;
            case AFNetworkReachabilityStatusNotReachable:
                showNetworkStatus(NO, AFNetworkReachabilityStatusNotReachable);
                break;
            case AFNetworkReachabilityStatusUnknown:
                showNetworkStatus(NO, AFNetworkReachabilityStatusUnknown);
                break;
            default:
                break;
        }
    }];
}

+ (void)cancelAllRequest {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.operationQueue cancelAllOperations];
}

@end
